package com.pctx.devicemanager.service.impl;

import com.pctx.common.util.DateTimeUtil;
import com.pctx.common.util.UuidUtil;
import com.pctx.devicemanager.dao.DeviceInfoMapper;
import com.pctx.devicemanager.pojo.DeviceInfo;
import com.pctx.devicemanager.pojo.DeviceInfoExample;
import com.pctx.devicemanager.pojo.DeviceUser;
import com.pctx.devicemanager.service.DeviceInfoService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by chason on 2018/2/28.19:06
 */
@Service("deviceInfoService")
public class DeviceInfoServiceImpl implements DeviceInfoService {
    @Autowired
    private DeviceInfoMapper deviceInfoMapper;

    @Override
    public List<DeviceInfo> getByCompanyUuid(String companyUuid) throws Exception {
        if (StringUtils.isEmpty(companyUuid))
            return null;

        DeviceInfoExample example = new DeviceInfoExample();
        DeviceInfoExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyUuidEqualTo(companyUuid);

        return deviceInfoMapper.selectByExample(example);
    }

    @Override
    public DeviceInfo getByUuid(String uuid) throws Exception {
        if (StringUtils.isEmpty(uuid))
            return null;

        DeviceInfoExample example = new DeviceInfoExample();
        DeviceInfoExample.Criteria criteria = example.createCriteria();
        criteria.andUuidEqualTo(uuid);

        List<DeviceInfo> list = deviceInfoMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list))
            return null;

        return list.get(0);
    }

    @Override
    public boolean add(DeviceInfo info) throws Exception {
        if (null == info)
            return false;

        info.setUuid(UuidUtil.randomUUID());
        info.setCreateTime(DateTimeUtil.nowDate());
        info.setUpdateTime(DateTimeUtil.nowDate());

        return deviceInfoMapper.insertSelective(info) > 0;
    }

    @Override
    public boolean updateByUuid(DeviceInfo info) throws Exception {
        if (null == info || StringUtils.isEmpty(info.getUuid()))
            return false;

        DeviceInfo old = getByUuid(info.getUuid());
        if (null == old)
            return false;

        info.setId(old.getId());
        info.setUpdateTime(DateTimeUtil.nowDate());

        return deviceInfoMapper.updateByPrimaryKeySelective(info) > 0;
    }

}
